/// @tags: DP
#include <cstdio>
#include <iostream>
#include <vector>

using namespace std;

namespace BlueQuantum {

typedef long long LL;
using LL = long long;
using u64 = unsigned long long;
using u32 = unsigned;

constexpr int P = 998244353;

struct Data {
  int max = 0;
  int cnt = 0;
};

Data operator+(const Data &a, const Data &b) {
  if (a.max > b.max) {
    return a;
  } else if (a.max < b.max) {
    return b;
  } else {
    return {a.max, (a.cnt + b.cnt) % P};
  }
}

inline int main() {
  int n;
  cin >> n;
  vector<int> c(3 * n);
  for (int i = 0; i < 3 * n; ++i) {
    cin >> c[i];
    c[i]--;
  }
  auto solve = [&](const vector<int> &a) {
    vector<int> last(n, -1);
    int m = a.size();
    vector<Data> dp(m + 1);
    dp[0] = {1, 1};
    for (int i = 0; i < m; ++i) {
      dp[i + 1] = dp[i];
      if (last[a[i]] != -1) {
        auto v = dp[last[a[i]]];
        v.max++;
        dp[i + 1] = dp[i + 1] + v;
      }
      last[a[i]] = i;
    }
    if (dp[m].max == n) {
      return dp[m].cnt;
    } else {
      return 0;
    }
  };
  int ans = 0;
  for (int i = 0; i < 3; ++i) {
    int u = find(c.begin() + 1, c.end(), c[0]) - c.begin();
    ans = (ans + solve(vector<int>(c.begin() + u + 1, c.end()))) % P;
    rotate(c.begin(), c.begin() + u, c.end());
  }
  cout << ans << "\n";
  return 0;
}

}  // namespace BlueQuantum

int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen("/tmp/CodeTmp/testdata.in", "r", stdin);
  freopen("/tmp/CodeTmp/testdata.out", "w", stdout);
#else
  freopen("arc.in", "r", stdin);
  freopen("arc.out", "w", stdout);
#endif
#endif

  ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  return BlueQuantum::main();
}
